import type { OptionItem } from "@/pages/internship/position/apis/type"
import type { PositionAddOrUpdateRequest, PositionDetail, PositionItem, PositionListQuery } from "@/pages/internship/position/position-teacher/apis/type"
import { ElMessage } from "element-plus"
import { defineStore } from "pinia"
import { reactive, ref } from "vue"
import { getPositionOptionsApi } from "@/pages/internship/position/apis/index"
import { addPositionApi, getPositionDetailForTeacherApi, getTeacherPositionListApi, updatePositionApi } from "@/pages/internship/position/position-teacher/apis"
import { pinia } from ".."
import { useUserStore } from "./user"

export const usePositionTeacherStore = defineStore("positionTeacher", () => {
  // 列表与分页状态
  const loading = ref(false)
  const list = ref<PositionItem[]>([])
  const total = ref(0)
  const query = reactive<PositionListQuery>({
    keyword: "",
    workType: undefined,
    workCity: undefined,
    period: undefined,
    salary: undefined,
    positionType: undefined,
    ignoreStatus: true,
    page: 1,
    size: 10,
    userId: 0
  })

  // 职位详情相关状态
  const positionDetail = ref<PositionDetail | null>(null)
  const isLoadingDetail = ref(false)
  const detailError = ref<string | null>(null)

  // 选项数据 - 参考position-student.ts实现
  const workTypeOptions = ref<OptionItem[]>([])
  const workCityOptions = ref<OptionItem[]>([])
  const periodOptions = ref<OptionItem[]>([])
  const salaryOptions = ref<OptionItem[]>([])
  const positionTypeOptions = ref<OptionItem[]>([])
  const companyOptions = ref<OptionItem[]>([])

  // 获取职位列表数据
  const fetchPositionList = async (isRefresh = false) => {
    if (isRefresh) {
      query.page = 1
    }
    // 从用户store获取用户ID
    const userStore = useUserStore(pinia)
    query.userId = userStore.userInfo?.userId || 0
    loading.value = true
    try {
      const response = await getTeacherPositionListApi(query)
      if (response?.data) {
        list.value = response.data.records || []
        total.value = response.data.total || 0
      }
    } catch (error) {
      console.error("获取职位列表失败:", error)
      ElMessage.error("获取职位列表失败")
    } finally {
      loading.value = false
    }
  }

  // 重置查询参数
  const resetQueryParams = () => {
    Object.assign(query, {
      keyword: "",
      workType: undefined,
      workCity: undefined,
      period: undefined,
      salary: undefined,
      positionType: undefined,
      ignoreStatus: true,
      page: 1,
      size: 10
    })
  }

  // 更新查询参数
  const updateQueryParams = (params: Partial<PositionListQuery>) => {
    Object.assign(query, params)
  }

  // 获取职位详情
  const fetchPositionDetail = async (positionId: number) => {
    // console.log("fetchPositionDetail被调用，职位ID:", positionId)
    isLoadingDetail.value = true
    detailError.value = null

    try {
      // console.log("开始调用getPositionDetailForTeacherApi")
      const response = await getPositionDetailForTeacherApi(positionId)

      if (response && response.data) {
        positionDetail.value = response.data
        return response.data
      } else {
        // console.warn("API响应数据为空")
        detailError.value = "获取职位详情失败：响应数据为空"
        return null
      }
    } catch (error: any) {
      console.error("获取职位详情失败:", error)
      detailError.value = error.message || "获取职位详情失败"
      return null
    } finally {
      isLoadingDetail.value = false
    }
  }

  // 重置职位详情状态
  const resetPositionDetail = () => {
    positionDetail.value = null
    isLoadingDetail.value = false
    detailError.value = null
  }

  // 新增职位
  const addPosition = async (reqVo: PositionAddOrUpdateRequest) => {
    try {
      const userStore = useUserStore()
      reqVo.publishUserId = userStore.userInfo?.userId || 0
      const response = await addPositionApi(reqVo)
      if (response?.data) {
        ElMessage.success("职位新增成功")
        return true
      } else {
        ElMessage.error("职位新增失败")
        return false
      }
    } catch (error) {
      console.error("新增职位失败:", error)
      ElMessage.error("新增职位失败")
      return false
    }
  }

  // 更新职位
  const updatePosition = async (reqVo: PositionAddOrUpdateRequest) => {
    try {
      const userStore = useUserStore()
      reqVo.publishUserId = userStore.userInfo?.userId || 0
      const response = await updatePositionApi(reqVo)
      if (response?.data) {
        ElMessage.success("职位更新成功")
        return true
      } else {
        ElMessage.error("职位更新失败")
        return false
      }
    } catch (error) {
      console.error("更新职位失败:", error)
      ElMessage.error("更新职位失败")
      return false
    }
  }

  // 获取选项数据的方法 - 参考position-student.ts实现
  const fetchOptions = async () => {
    try {
      const response = await getPositionOptionsApi()
      if (response && response.data) {
        const optionsData = response.data

        // 设置各选项数据，确保类型安全
        workTypeOptions.value = optionsData.workTypeOptions || []
        workCityOptions.value = optionsData.workCityOptions || []
        periodOptions.value = optionsData.periodOptions || []
        salaryOptions.value = optionsData.salaryOptions || []
        positionTypeOptions.value = optionsData.positionTypeOptions || []
        companyOptions.value = optionsData.companyOptions || []
      }
    } catch (error) {
      console.error("获取选项数据失败:", error)
      // 错误时使用默认数据作为备选
      applyDefaultOptions()
    }
  }

  const applyDefaultOptions = () => {
    workTypeOptions.value = [
      { value: 14, label: "线下实习" },
      { value: 15, label: "线上实习" },
      { value: 16, label: "混合模式" }
    ]
    workCityOptions.value = [
      { value: 24, label: "上海市" },
      { value: 25, label: "广东省" },
      { value: 26, label: "江苏省" },
      { value: 27, label: "浙江省" },
      { value: 28, label: "北京市" }
    ]
    periodOptions.value = [
      { value: 9, label: "1个月" },
      { value: 10, label: "3个月" },
      { value: 11, label: "6个月" },
      { value: 12, label: "6个月以上" }
    ]
    salaryOptions.value = [
      { value: 18, label: "无" },
      { value: 19, label: "3000元/月以下" },
      { value: 20, label: "3000-4000元/月" },
      { value: 21, label: "4000-5000元/月" },
      { value: 22, label: "5000元/月以上" }
    ]
    positionTypeOptions.value = [
      { value: 2, label: "Java开发实习生" },
      { value: 3, label: "前端开发实习生" },
      { value: 4, label: "UI设计实习生" },
      { value: 5, label: "产品经理实习生" },
      { value: 6, label: "人力资源实习生" },
      { value: 7, label: "市场推广实习生" }
    ]
    console.log("已应用默认选项数据")
  }

  // 根据选项标签获取对应的值 - 从PositionEditModal.vue中整合
  const getOptionValue = (label: string, options: OptionItem[]): number => {
    const option = options.find(opt => opt.label === label)
    return option ? option.value : 0
  }

  return {
    // 状态
    loading,
    list,
    total,
    query,
    positionDetail,
    isLoadingDetail,
    detailError,
    // 选项数据
    workTypeOptions,
    workCityOptions,
    periodOptions,
    salaryOptions,
    positionTypeOptions,
    companyOptions,
    // 方法
    fetchPositionList,
    resetQueryParams,
    updateQueryParams,
    fetchPositionDetail,
    resetPositionDetail,
    addPosition,
    fetchOptions,
    updatePosition,
    applyDefaultOptions,
    getOptionValue
  }
})

/**
 * @description 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * @description 在 SSR 应用中可用于在 setup 外使用 store
 */
export function usePositionTeacherStoreOutside() {
  return usePositionTeacherStore(pinia)
}
